﻿using System.Text;

namespace QuantBox.XApi
{
    public class UfxTrader : IXApi
    {
        private UfxClient? _client;

        public void RegisterSpi(IXSpi spi)
        {
            _client ??= new UfxClient(spi);
        }

        public void Release()
        {
            _client?.Release();
            _client = null;
        }

        public void Connect(ServerInfoField server, UserInfoField user)
        {
            Server = server;
            User = user;
            UserLogin = null;
            _client?.Connect(server, user);
        }

        public void Disconnect()
        {
            _client?.Disconnect();
        }

        public void Query(QueryType type, ReqQueryField query)
        {
            _client!.Query(type);
        }

        public void Subscribe(string instrument, string exchange, InstrumentType type)
        {
        }

        public void Unsubscribe(string instrument, string exchange, InstrumentType type)
        {
        }

        public string SendOrder(params OrderField[] orders)
        {
            if (orders.Length == 1) {
                return _client!.SendOrder(orders[0]);
            }
            var result = new StringBuilder();
            foreach (var order in orders) {
                if (result.Length > 0) {
                    result.Append(",");
                }
                result.Append(_client!.SendOrder(order));
            }
            return result.ToString();
        }

        public string CancelOrder(params string[] list)
        {
            foreach (var id in list) {
                _client!.CancelOrder(id);
            }
            return string.Empty;
        }

        public string ApiVersion => GetType().Assembly.GetName().Version.ToString();
        public ApiType ApiTypes => ApiType.Trade | ApiType.Query;
        public string ApiName => "UFX";

        public bool Connected => _client?.Connected ?? false;
        public ServerInfoField? Server { get; private set; }
        public UserInfoField? User { get; private set; }
        public RspUserLoginField? UserLogin { get; internal set; }
    }
}
